package org.example.view.admin;

import org.example.controller.AdminController;
import org.example.data.Result;
import org.example.data.Room;
import org.example.data.UserWithDetails;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

public class UpdateRoom extends JFrame {
    private JTextField txtRoomId, txtNewName, txtNewFloor, txtNewPrice;
    private JButton btnUpdate;
    private UserWithDetails user;

    public UpdateRoom(UserWithDetails user) {
        super("更新房间信息");
        this.user = user;
        initUI();
        setSize(400, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    private void initUI() {
        JPanel panel = new JPanel(new GridLayout(5, 2));

        JLabel lblRoomId = new JLabel("房间ID:");
        JLabel lblNewName = new JLabel("新名称:");
        JLabel lblNewFloor = new JLabel("新楼层:");
        JLabel lblNewPrice = new JLabel("新价格:");

        txtRoomId = new JTextField();
        txtNewName = new JTextField();
        txtNewFloor = new JTextField();
        txtNewPrice = new JTextField();

        btnUpdate = new JButton("更新");
        btnUpdate.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    int roomId = Integer.parseInt(txtRoomId.getText());
                    String newName = txtNewName.getText();
                    String newFloor = txtNewFloor.getText();
                    double newPrice = Double.parseDouble(txtNewPrice.getText());

                    Room updatedRoom = new Room(newName, newFloor, newPrice);
                    AdminController adminController = new AdminController();
                    Result<Boolean> result = adminController.updateRoom(updatedRoom, roomId);
                    if (result.getStatus()) {
                        JOptionPane.showMessageDialog(UpdateRoom.this, "房间信息更新成功！");
                        SwingUtilities.invokeLater(() -> new AdminIndex(user).setVisible(true));
                        dispose(); // 关闭窗口
                    } else {
                        JOptionPane.showMessageDialog(UpdateRoom.this, result.getMessage());
                    }
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(UpdateRoom.this, "请输入有效的数字！");
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(UpdateRoom.this, "数据库操作错误：" + ex.getMessage());
                }
            }
        });

        panel.add(lblRoomId);
        panel.add(txtRoomId);
        panel.add(lblNewName);
        panel.add(txtNewName);
        panel.add(lblNewFloor);
        panel.add(txtNewFloor);
        panel.add(lblNewPrice);
        panel.add(txtNewPrice);
        panel.add(new JLabel()); // 填充
        panel.add(btnUpdate);

        add(panel);
    }

}
